//引入SweetAlert弹出层js
document.write("<script src='https://cdn.bootcss.com/limonte-sweetalert2/7.21.1/sweetalert2.all.js'></script>");

var num = 0; //使用数字键输入的数字

// ATM对象
var atm = {status:0}; // 0:空闲 1:关闭 2:处理中
atm.refresh = function refresh(status){
	this.status = status;
}

// 屏幕对象
var display = {text:""};
display.refresh = function refresh(text){
	this.text = text;
	$("#display").html(this.text);
}
display.show = function show(text){
	$("#display").html(text);
}

//收据口
var receipt = {text:""};
receipt.refresh = function refresh(text){
	this.text = text;
	$("#area").html(text);
}

// 按钮对象
var switchButton = {text:"",disable:true}; 
switchButton.refresh = function refresh(text,disable){
	this.text = text;
	this.disable = disable;
	$("#switch").val(text);
	$("#switch").unbind("click");
	if(atm.status == 0){
		$("#switch").click(turnoff);
		//空闲状态 禁止 确认  取消按钮
		$("#comfirm").attr("disabled", "disabled");
		$("#cancel").attr("disabled", "disabled");
		$("#switch").removeAttr("disabled");
	}
	else if(atm.status == 1){
		$("#switch").click(turnon);	
		//关机状态  禁止 确认  取消按钮
		$("#comfirm").attr("disabled", "disabled");
		$("#cancel").attr("disabled", "disabled");
	}
	else if(atm.status == 2){
		//处理状态 
		$("#comfirm").removeAttr("disabled", "disabled");
		$("#cancel").removeAttr("disabled", "disabled");
		$("#switch").attr("disabled", "disabled");
	}
	$("#switch").attr('disable',disable);
}

// 插卡孔
var cardSlot = {text:"",inserted:false};
cardSlot.refresh = function refresh(text,inserted){
	this.text = text;
	this.inserted = inserted;
	$("#card").html(text);
	if(inserted){
		$("#card").attr('disabled', inserted);
	}else{
		$("#card").removeAttr('disabled');
	}
}

//存取款口
var moneyBox = {money:0,state:0};
moneyBox.refresh = function refresh(money, state){
	this.money = money;
	this.state = state;
	var box = $("#money_box");
	var text;
	box.removeAttr('onclick');
	switch(state){
	//关闭状态
	case 0:
		//改变原有状态样式图片，用$("#money.box")报错
		document.getElementById("money_box").style.backgroundImage = 'url(image/money_close.png)';
		break;
	//待放款状态
	case 1:
		box.attr('onclick', 'putMoney()');
		document.getElementById("money_box").style.backgroundImage = 'url(image/money_put.png)';
		break;
	//待取款状态
	case 2:
		document.getElementById("money_box").style.backgroundImage = 'url(image/money.png)';
		box.attr('onclick', 'getMoney('+money+')');
		break;
	}
	
}

// 数字按钮
var digitButton = {state:2,visibility:0,servletName:""};
digitButton.refresh = function refresh(state,visibility,servletName){
	this.state = state;
	this.visibility = visibility;
	this.servletName = servletName;
	//如果为单输入或不可输入状态，则不需要确认按钮，因此关闭确认、取消按钮
	if(state == 0 || state == 2){
		$("#comfirm").attr("disabled", "disabled");
/*		$("#cancel").attr("disabled", "disabled");*/
	}else{
		$("#comfirm").removeAttr("disabled");
		$("#cancel").removeAttr("disabled");
	}
}
	
function readNum(obj){
	var digit = Number(obj.value);
	if(digitButton.state == 0){
		submitNum(digit);
	}
	else if(digitButton.state == 1){
		num = 10*num + digit;
		var str = display.text+"<br/>";
		str+=num;
		//如果是输入密码则隐藏
		if(digitButton.visibility == 1){
			var paw = '';
			for(var i=0;i<num.toString().length;i++){
				paw += '*';
			}
			display.show(display.text+"<br/>"+paw);
		}else{
			display.show(str);
		}
	}
	else if(digitButton.state == 2){
		
	}
}

$(document).ready(function() {
	$("#card").click(insertCard);
	getStatus();
});

function refresh(resp){
	console.log(resp);
	atm.refresh(resp.ATM.state);
	display.refresh(resp.display.text);
	switchButton.refresh(resp.switchbutton.text,resp.switchbutton.disable);
	cardSlot.refresh(resp.cardslot.text,resp.cardslot.inserted);
	digitButton.refresh(resp.digitbutton.state,resp.digitbutton.visibility,resp.digitbutton.servletName);
	moneyBox.refresh(resp.moneyBox.money, resp.moneyBox.state);
	receipt.refresh(resp.receipt.text);
}

function getStatus(){
	
	$.post('/ATM/GetStatusServlet', function(responseText) {
		refresh(responseText);
	});
}

function turnon(){
	//开关机需要验证管理员密码
	swal({
		  title: '请输入管理员密码',
		  input: 'password',
		  showCancelButton: true,
		  confirmButtonText: '确认',
		  showLoaderOnConfirm: true,
		  allowOutsideClick: false
		}).then(	//接着执行
		   function (value) {
			   if(value.value == 8888){
				   $.post('/ATM/TurnOnServlet', function(responseText) {
						refresh(responseText);
					});
			   }else{
				   swal(
						  '错误',
						  '管理员密码错误',
						  'error'
						)
					return;
			   }
		}
		);
	
}

function turnoff(){
	//开关机需要验证管理员密码
	swal({
		  title: '请输入管理员密码',
		  input: 'password',
		  showCancelButton: true,
		  confirmButtonText: '确认',
		  showLoaderOnConfirm: true,
		  allowOutsideClick: false
		}).then(	//接着执行
		   function (value) {
			   if(value.value == 8888){
				   $.post('/ATM/TurnOffServlet', function(responseText) {
						refresh(responseText);
					});
			   }else{
				   swal(
						  '错误',
						  '管理员密码错误',
						  'error'
						)
					return;
			   }
		}
		);
	
}

function insertCard(){
	swal({
		  title: '请插入银行卡',
		  input: 'text',
		  showCancelButton: true,
		  confirmButtonText: '确认',
		  showLoaderOnConfirm: true,
		  //提交前函数
		  preConfirm: function(value) {
		  	//校验函数
		    return new Promise(function(resolve, reject) { //返回resolve()为通过，reject()拒绝
		      //校验是否数字
		        if (!isNaN(value)) {
		          resolve();
		        } else {
		            swal(
				    '卡号格式有误！',
				    '请重新插入',
				    'warning'
				  ); 
		        }
		    });
		  },
		  allowOutsideClick: false
		}).then(	//接着执行
		   function (value) {
			   if(value.value == undefined || value.value == ''){
				   return;
			   }
			   cardNo = value.value;
			   $.post('/ATM/CardInsertedServlet','cardNo='+cardNo, function(responseText) {
					refresh(responseText);
				});	
		}
		);
	
}

function submitNum(number){
	$.post('/ATM/'+digitButton.servletName,'num='+number, function(responseText) {
		refresh(responseText);
		num = 0;
	});
}

/**
 * 取消\返回按钮
 */
function cancel(){
	//置空输入内容
	num = 0;
	display.show(display.text+"<br/>");
	//当转入账号无效时，点击取消返回主菜单
	if(digitButton.state == 2){
		$.post('/ATM/'+digitButton.servletName, function(responseText) {
			refresh(responseText);
		});
	}
}

function submit(){
	//当未插卡时或ATM空闲时，禁用确认操作，防止密码错误三次后还能继续点击
	if(!(cardSlot.inserted)){
		return;
	}
	submitNum(num);
}

//取走现金
function getMoney(money){
	swal('您已取走现金'+money+'元');
	$.post('/ATM/TurnOffMoneyBoxServlet', function(responseText) {
		moneyBox.refresh(money, responseText.moneyBox.state);
	});
}

//放入现金
function putMoney(){
	
	swal({
		  title: '放入现金/元，只支持面值为100元的纸币',
		  input: 'text',
		  showCancelButton: true,
		  confirmButtonText: '确认',
		  showLoaderOnConfirm: true,
		  //提交前函数
		  preConfirm: function(value) {
		  	//校验函数
		    return new Promise(function(resolve, reject) { //返回resolve()为通过，reject()拒绝
		      //校验是否数字
		        if((isNaN(value) || value%100) != 0){
		    		swal(
					    '面值有误，只支持面值为100的纸币！',
					    '请重新插入',
					    'warning'
		    		); 
		    	}else{
		    		resolve();
		    	}
		    });
		  },
		  allowOutsideClick: false
		}).then(	//接着执行
		   function (value) {
			    num += value.value;
				//更新显示
				display.refresh(display.text + '<br>' + '放入现金' + value.value + '元');
				//开启确认按钮
				$("#comfirm").removeAttr('disabled');
		   }
	);

	
}
